<template>
  <el-card class="form-container" shadow="never">
    <div v-for="(cate, index) in allResourceCate" :class="index === 0 ? 'top-line' : null" :key="'cate' + cate.id">
      <el-row class="table-layout" style="background: #F2F6FC;">
        <el-checkbox
            v-model="cate.checked"
            :indeterminate="isIndeterminate(cate.id)"
            @change="handleCheckAllChange(cate)"
        >
          {{ cate.name }}
        </el-checkbox>
      </el-row>
      <el-row class="table-layout">
        <el-col :span="8" v-for="resource in getResourceByCate(cate.id)" :key="resource.id" style="padding: 4px 0">
          <el-checkbox v-model="resource.checked" @change="handleCheckChange(resource)">
            {{ resource.name }}
          </el-checkbox>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleClear">清空</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { fetchAllResourceList } from '@/api/resource';
import {allocResource,listResourceByRole} from '@/api/role';
import { listAllCate } from '@/api/resourceCategory';

const route = useRoute();
const router = useRouter();

const roleId = ref(route.query.roleId);
const allResource = ref([]);
const allResourceCate = ref([]);

// 获取所有资源分类列表
const getAllResourceCateList = async () => {
  try {
    const response = await listAllCate();
    allResourceCate.value = response.data.data.map(cate => ({ ...cate, checked: false }));
    await getAllResourceList();
  } catch (error) {
    console.error('Error fetching resource categories:', error);
    ElMessage({
      message: '获取资源分类失败，请重试',
      type: 'error',
      duration: 1000
    });
  }
};

// 获取所有资源列表
const getAllResourceList = async () => {
  try {
    const response = await fetchAllResourceList();
    allResource.value = response.data.data.map(resource => ({ ...resource, checked: false }));
    await getResourceByRole(roleId.value);
  } catch (error) {
    console.error('Error fetching resources:', error);
    ElMessage({
      message: '获取资源失败，请重试',
      type: 'error',
      duration: 1000
    });
  }
};

// 根据角色获取已分配资源
const getResourceByRole = async (roleId) => {
  try {
    const response = await listResourceByRole(roleId);
    const allocResource = response.data.data || [];
    allResource.value.forEach(item => {
      item.checked = getResourceChecked(item.id, allocResource);
    });
    allResourceCate.value.forEach(item => {
      item.checked = isAllChecked(item.id);
    });
  } catch (error) {
    console.error('Error fetching allocated resources:', error);
    ElMessage({
      message: '获取已分配资源失败，请重试',
      type: 'error',
      duration: 1000
    });
  }
};

// 检查资源是否已被分配
const getResourceChecked = (resourceId, allocResource) => {
  return allocResource.some(allocRes => allocRes.id === resourceId);
};

// 获取指定分类下的资源
const getResourceByCate = (categoryId) => {
  return allResource.value.filter(resource => resource.categoryId === categoryId);
};

// 判断全选按钮是否处于不确定状态
const isIndeterminate = (categoryId) => {
  const cateResources = getResourceByCate(categoryId);
  if (!cateResources.length) return false;
  const checkedCount = cateResources.filter(res => res.checked).length;
  return checkedCount > 0 && checkedCount < cateResources.length;
};

// 判断分类下所有资源是否都被选中
const isAllChecked = (categoryId) => {
  const cateResources = getResourceByCate(categoryId);
  if (!cateResources.length) return false;
  return cateResources.every(res => res.checked);
};

// 保存分配的资源
const handleSave = async () => {
  try {
    await ElMessageBox.confirm('是否分配资源？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 获取所有选中的资源 ID
    const checkedResourceIds = allResource.value.filter(res => res.checked).map(res => res.id);

    // 创建 URLSearchParams 对象
    const params = new URLSearchParams();
    params.append("roleId", roleId.value);

    // 如果有选中的资源 ID，则添加到参数中
    if (checkedResourceIds.length > 0) {
      params.append("resourceIds", checkedResourceIds.join(',')); // 使用逗号分隔的字符串
    } else {
      params.append("resourceIds", ""); // 如果没有选中的资源，传递空字符串
    }

    // 发送请求
    await allocResource(params.toString());

    // 处理成功响应
    ElMessage({
      message: '分配成功',
      type: 'success',
      duration: 1000
    });

    // 返回上一页
    router.back();
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('Error allocating resources:', error);
      ElMessage({
        message: '分配资源失败，请重试',
        type: 'error',
        duration: 1000
      });
    }
  }
};

// 清空选择
const handleClear = () => {
  allResourceCate.value.forEach(item => item.checked = false);
  allResource.value.forEach(item => item.checked = false);
};

// 全选/取消全选
const handleCheckAllChange = (cate) => {
  const cateResources = getResourceByCate(cate.id);
  cateResources.forEach(res => res.checked = cate.checked);
};

// 单个资源选择变化
const handleCheckChange = (resource) => {
  const cate = allResourceCate.value.find(c => c.id === resource.categoryId);
  if (cate) {
    cate.checked = isAllChecked(cate.id);
  }
};

onMounted(() => {
  getAllResourceCateList();
});
</script>

<style scoped>
.table-layout {
  padding: 20px;
  border-left: 1px solid #DCDFE6;
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
}

.top-line {
  border-top: 1px solid #DCDFE6;
}
</style>